import json
import logging
import os
import time

import mplfinance as mpf
from matplotlib.pyplot import savefig

import okex.v5.market_api as market
from Indicators import Boll
from main import get_current_history_candles
from tools import picture_upload
from tools.dingdingrobot import call_dingtalk
from tools.send_mail import send_email

# 通过行情数据, 实时计算给定品种的Boll值, 并推送





if __name__ == '__main__':

    # param test's value is False if is True will use simulate trading

    base_dir = r"./"
    bar = '15m'

    with open(os.path.join(base_dir, "passwords", "passwords.json"), 'r') as f:
        data = json.load(f)

    # 模拟盘api
    api_key = data[0]['api_key']
    secret_key = data[0]['secret_key']
    passphrase = data[0]['passphrase']


    obj = dict([('api_key', api_key), ('secret_key', secret_key), ('passphrase', passphrase)])

    api_key = obj['api_key']
    secret_key = obj['secret_key']
    passphrase = obj['passphrase']

    instIds = ['BTC-USDT-SWAP', 'ETH-USDT-SWAP','DOGE-USDT-SWAP','XRP-USDT-SWAP','LTC-USDT-SWAP','ADA-USDT-SWAP','SOL-USDT-SWAP','DOT-USDT-SWAP']

    # 设置日志存储位置
    LOG_DIR = os.path.join(base_dir, "./log")
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    LOG_ADDR = os.path.join(LOG_DIR, 'chooseLog.log')
    logging.basicConfig(filename=LOG_ADDR,format='%(asctime)s - %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
    logger = logging.getLogger(__name__)
    logger.info("start")

    # 图片保存位置
    pic_dir = os.path.join(base_dir, "./pictures")
    if not os.path.exists(pic_dir):
        os.makedirs(pic_dir)

    # 市场行情API
    marketAPI = market.MarketAPI(api_key, secret_key, passphrase, use_server_time=False, test=True)
    marketAPI.set_api_url("https://www.okx.com")

    #每隔5分钟检测一下, 如果当前价格上传布林上轨, 或者低于布林下轨就提醒
    while True:
        try:
            for instId in instIds:
                history_candles = get_current_history_candles(marketAPI, instId, bar=bar)
                # 获取布林带算过的history_candles
                bolling_candles = Boll.Boll(history_candles, 20, 2)

                # 当前K线收盘价c高于上轨或者低于下轨时进行推送
                if bolling_candles['Close'][-1] > bolling_candles['UpperBand'][-1] or bolling_candles['Close'][-1] < bolling_candles['LowerBand'][-1]:
                    # 创建Bollinger Bands的添加线
                    apds = [
                        mpf.make_addplot(bolling_candles['MiddleBand'], color='blue'),
                        mpf.make_addplot(bolling_candles['UpperBand'], color='red'),
                        mpf.make_addplot(bolling_candles['LowerBand'], color='green'),
                        mpf.make_addplot(bolling_candles['BoolingDiff'], color='yellow')
                    ]
                    save_path = "./pictures/demo/{}.png".format(instId)
                    mpf.plot(bolling_candles, type='candle', addplot=apds, style='default', volume=True,savefig=save_path)
                    # 绘制并推送图片到钉钉
                    message = []
                    pic_path = picture_upload.upload(save_path)
                    message.append("行情提示")
                    message.append("{} Bollinger Bands指标".format(instId))
                    call_dingtalk(message, 'news', picurl=pic_path,test=False)
                    send_email("{} 机会出现!".format(instId),subject="{} 机会出现".format(instId))
            time.sleep(600)
        except:
            logger.error("error")